package top.yxf.mcp.server.juejing.infrastructure.adapter;

import ch.qos.logback.core.util.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;
import top.yxf.mcp.server.juejing.domain.adapter.IJuejinPort;
import top.yxf.mcp.server.juejing.domain.model.ArticleFunctionRequest;
import top.yxf.mcp.server.juejing.domain.model.ArticleFunctionResponse;
import top.yxf.mcp.server.juejing.infrastructure.gateway.IJueJingService;
import top.yxf.mcp.server.juejing.infrastructure.gateway.dto.JueJinCreateArticleRequestDTO;
import top.yxf.mcp.server.juejing.infrastructure.gateway.dto.JueJinCreateArticleResponseDTO;
import top.yxf.mcp.server.juejing.infrastructure.gateway.dto.JueJinPublishRequestDTO;
import top.yxf.mcp.server.juejing.infrastructure.gateway.dto.JueJinPublishResponseDTO;
import top.yxf.mcp.server.juejing.type.properties.JueJinApiProperties;

import java.util.Collections;

@Component
@Slf4j
public class JueJinPort implements IJuejinPort {


    @Resource
    private JueJinApiProperties jueJinApiProperties;

    @Resource
    private IJueJingService jueJingService;

    /**
     * 文章发布
     *
     * @param request 参数
     * @return CreateArticleFunctionResponse
     * @throws Exception
     */
    @Override
    public ArticleFunctionResponse writeArticle(ArticleFunctionRequest request) throws Exception {

        if (request == null) {
            log.error("JueJinPort.createArticleFunction request is null");
            throw new Exception("request is null");
        }
        if (StringUtil.isNullOrEmpty(request.getBriefContent()) ||request.getBriefContent().length() < 50  || request.getBriefContent().length() > 100) {
            log.error("JueJinPort.createArticleFunction briefContent is null or length is not in [50,100]");
            throw new Exception("briefContent is null or length is not in [50,100]");
        }
        // 如果为空 则使用默认值
        if (request.getTagIds() == null || request.getTagIds().isEmpty()) {
            request.setTagIds(jueJinApiProperties.getTagIds());
        }
        // 创建文章
        log.info("JueJinPort.createArticleFunction request: {}" , request );
        JueJinCreateArticleRequestDTO jueJinCreateArticleRequestDTO = new JueJinCreateArticleRequestDTO();
        jueJinCreateArticleRequestDTO.setTitle(request.getTitle());
        jueJinCreateArticleRequestDTO.setBrief_content(request.getBriefContent());
        jueJinCreateArticleRequestDTO.setMark_content(request.getMarkContent());
        jueJinCreateArticleRequestDTO.setPics(request.getPics());
        jueJinCreateArticleRequestDTO.setTheme_ids(request.getThemeIds());
        jueJinCreateArticleRequestDTO.setCategory_id(jueJinApiProperties.getCategoryId());
        jueJinCreateArticleRequestDTO.setTag_ids(request.getTagIds());
        Call<JueJinCreateArticleResponseDTO> article = jueJingService.createArticle(jueJinApiProperties.getCookie(), jueJinCreateArticleRequestDTO);
        log.info("JueJinPort.createArticleFunction dto: {}" , jueJinCreateArticleRequestDTO);
        Response<JueJinCreateArticleResponseDTO> response = article.execute();
        log.info("JueJinPort.createArticleFunction response: {}" , response.body() );
        if (response.isSuccessful() && response.body() != null) {
            JueJinCreateArticleResponseDTO result = response.body();
            if (result.getErr_no() == 0) {
                log.info("创掘金文章成功，文章ID（草稿ID）：{}", result.getData().getId());
                log.info("该ID将用于后续发布文章的draft_id参数");
                System.out.println("创建成功，文章ID: " + result.getData().getId());
                // 发布文章
                JueJinPublishRequestDTO jueJinPublishRequestDTO = new JueJinPublishRequestDTO();
                jueJinPublishRequestDTO.setDraft_id(result.getData().getId());
                jueJinPublishRequestDTO.setTheme_ids(Collections.emptyList());
                jueJinPublishRequestDTO.setColumn_ids(Collections.emptyList());
                jueJinPublishRequestDTO.setEncrypted_word_count(1);
                jueJinPublishRequestDTO.setOrigin_word_count(request.getMarkContent().length());
                Call<JueJinPublishResponseDTO> jueJinPublishResponseDTOCall = jueJingService.publishArticle(jueJinApiProperties.getCookie(), jueJinPublishRequestDTO);
                Response<JueJinPublishResponseDTO> execute = jueJinPublishResponseDTOCall.execute();
                if (execute.isSuccessful() && execute.body() != null) {
                    JueJinPublishResponseDTO publicResult = execute.body();
                    if (publicResult.getErr_no() == 0) {
                        log.info("发布掘金文章成功，文章ID：{}", publicResult.getData().getArticle_id());
                        System.out.println("发布成功，文章ID: " + publicResult.getData().getArticle_id());
                        ArticleFunctionResponse articleFunctionResponse = new ArticleFunctionResponse();
                        articleFunctionResponse.setCode(publicResult.getErr_no());
                        articleFunctionResponse.setMsg(publicResult.getErr_msg());
                        ArticleFunctionResponse.SourceData sourceData = new ArticleFunctionResponse.SourceData();
                        sourceData.setArticleId(publicResult.getData().getArticle_id());
                        sourceData.setTitle(publicResult.getData().getTitle());
                        sourceData.setLinkUrl(publicResult.getData().getLink_url());
                        sourceData.setAuditStatus(publicResult.getData().getAudit_status());
                        sourceData.setRtime(publicResult.getData().getRtime());
                        articleFunctionResponse.setData(sourceData);
                        return articleFunctionResponse;
                    } else {
                        log.error("发布掘金文章失败，错误信息：{}", publicResult.getErr_msg());
                        System.out.println("发布失败，错误信息: " + publicResult.getErr_msg());
                    }
                } else {
                    log.error("发布掘金文章请求失败，错误码：{}", response.code());
                    System.out.println("请求失败，错误码：" + response.code());
                }
            } else {
                log.error("创建掘金文章失败，错误信息：{}", result.getErr_msg());
            }
        }

        return null;
    }
}
